import { Context } from 'koa'
import { success, insert, select, getSelectListSql, getLikeKeys, getPageQuery, update, deleteRow } from '../utils/index'
import { pool } from '../config/db'
import { Base64 } from 'js-base64'
import { simpleGit } from 'simple-git'
import { developController } from './develop'

export class TableConfigController {
  // 静态方法，获取列表
  static async getList(ctx: Context) {
    const { name = '', systemId, pathname, branch_id, status } = ctx.request.body as any
    const { size, offset } = getPageQuery(ctx.request.body || {})
    const sql = getSelectListSql(
      'table_config',
      getLikeKeys(
        ['name', 'pathname', 'systemId', 'branch_id', 'status'],
        [name, pathname, systemId, branch_id, status],
        [0, 1]
      )
    ) // 'SELECT * FROM table_config WHERE name LIKE ? LIMIT ?, ?'
    const [rows] = await pool.execute(
      sql,
      getLikeKeys(
        [name, pathname, systemId, branch_id, status, offset, size],
        [name, pathname, systemId, branch_id, status, offset, size],
        [0, 1]
      )
    )
    const [rows2]: [any, any] = await pool.execute('SELECT COUNT(*) AS count FROM table_config')
    ctx.body = success(ctx, { list: rows, totalRows: rows2[0].count })
  }
  static async create(ctx: Context) {
    const { name, apiTablePathName, hasTableBtn, config, systemId, branch_id, pathname } = ctx.request.body as any
    await insert('table_config', {
      name,
      systemId,
      pathname,
      apiTablePathName,
      hasTableBtn,
      config: JSON.stringify(config),
      branch_id,
      modifyTime: Date.now(),
      modifier: ctx.request.headers.nickname
    })
    ctx.body = success(ctx)
    ctx.state.logUser = { table: 'table_config', id: '' }
  }
  // 将弹窗配置更新到config中
  static async updateDialogConfig(ctx: Context) {
    const { apiDialogPathName, hasDialog, config, id } = ctx.request.body as any
    const [rows]: [any, any] = (await select('table_config', { id })) as [any, any]
    const oldConfig = JSON.parse(Base64.decode(rows[0]?.config)) || {}
    const newConfig = JSON.parse(Base64.decode(config)) || {}
    await update(
      'table_config',
      { id },
      {
        hasDialog,
        apiDialogPathName,
        config: Base64.encode(JSON.stringify({ ...oldConfig, ...newConfig })),
        modifyTime: Date.now(),
        modifier: ctx.request.headers.nickname
      }
    )
    ctx.body = success(ctx)
  }
  // config更新
  static async updateConfig(ctx: Context) {
    const { config, id } = ctx.request.body as any
    await update('table_config', { id }, { config, modifyTime: Date.now(), modifier: ctx.request.headers.nickname })
    ctx.body = success(ctx)
  }

  // 更新代码
  static async updateCode(ctx: Context) {
    const { id, hasConfig } = ctx.request.body as any
    await update(
      'table_config',
      { id },
      { hasCode: 1, status: hasConfig ? 1 : 2, modifyTime: Date.now(), modifier: ctx.request.headers.nickname }
    )
    await developController.saveFileCode(ctx)
    await developController.signFileModify(ctx)
    ctx.body = success(ctx)
  }
  // 删除
  static async delete(ctx: Context) {
    const { id, config, hasCode } = ctx.request.body as any
    if (config) {
      await deleteRow('table_config', { id })
    } else {
      await update('table_config', { id }, { status: -1 })
    }
    hasCode && (await developController.delFile(ctx))
    ctx.body = success(ctx)
  }
  // 空接口
  static async emptyApi(ctx: Context) {
    /*  const git = simpleGit({
      baseDir: 'D:/Ethan/work/web-admin-codes',
      binary: 'git',
      maxConcurrentProcesses: 6,
      trimmed: false
    })
    try {
      await git.init()
      await git.addRemote('origin', 'https://gitee.com/ethan6/test.git')
    } catch (e) {
    //   handle all errors here
    } */
    ctx.body = success(ctx, { list: [{}], totalRows: 1000 })
  }
}
